<?php

class Third_Acl extends Zend_Acl
{
	protected $cache;
	protected $auth;

    public function __construct(Zend_Auth $auth)
    {
        // INICIA CACHE
    	$this->cache = Zend_Registry::get ( 'cache' );

			//LOAD SITE INFOS
			$this->site = Zend_Registry::get('site');

			//PRIVILEGIOS DO SITE
			$id = $this->site['id'];

				require_once("PrivilegiosSites.php");
				$privilegiosSitesDao = new PrivilegiosSites();

				//PRIVILEGIOS DO USUARIO
				$usuario = $auth->getStorage()->read();

				$nivel = "";
				if($usuario)
					$nivel = $usuario->nivel;
									
				$cacheId = 'grupos_privilegios_sites_'.$id.'_nivel_'.$nivel;
				
				if( $this->cache->test($cacheId) ){
					$privilegegioDoSite = $this->cache->load($cacheId);
				} else {
					$privilegegioDoSite = $privilegiosSitesDao->getPrivelegiosByNivel( $id, $nivel );
					$this->cache->save($privilegegioDoSite, $cacheId, array('grupos', 'privilegios', 'sites'));
				}

				$privileges = array();
				foreach( $privilegegioDoSite as $p ){
					$privileges[] = $p; 
				}
			//END PRIVILEGIOS DO SITE	


			//MODULOS
			$modules = Zend_Registry::get('registered_modules');
	    	foreach( $modules as $key=>$value ){ //ADICIONA RESOURCES PARA MODULOS
			        $this->add(new Zend_Acl_Resource( $key ));
			}

			//ADICIONA GRUPO AS REGRAS
				// REGRAS DO SITE
				$siteNivel = $this->site['profile'];
				$this->addRole(new Zend_Acl_Role( $siteNivel ));
				$this->addDefaultPermissions( $siteNivel );

				//REGRAS DO LOGADO
				if( !($this->hasRole( $nivel ) ) ){
					$this->addRole(new Zend_Acl_Role( $nivel ));
					$this->addDefaultPermissions( $nivel );
				}
				
				//REGRAS DO VISITANTE
				$this->addRole(new Zend_Acl_Role( 'visitante' ));
				$this->addDefaultPermissions( 'visitante' );
				
			//ADICIONA RESOURCES PARA CONTROLLERS E ACTIONS
			foreach( $privileges as $r){
				
					if( !($this->has( $r['regra'] ) ) && !empty( $r['action'] ) ){
			        	$this->add(new Zend_Acl_Resource( $r['regra'], $r['module'] ) );
					}
					
				//ADICIONA REGRA
				if(  !empty( $r['action']  ) )
					$this->allow( $nivel , $r['regra'] );
			}

			//REGISTRA OS PRIVILEGIOS
			Zend_Registry::set('privileges', $privileges );
	}
	
	function addDefaultPermissions( $role ){
			$defaultAdd = array( 
				'third:index:index' ,
				'third:login:index' ,
				'third:login:logout',
				'default:index:index',
				'third:error:login',
				'third:error:privileges',
				'default',
				'clientes:index:index'
			);
				
			foreach( $defaultAdd as $regra ){
			 	if( !($this->has( $regra ) ) ){
			 		$this->add(new Zend_Acl_Resource( $regra ) );
			 	}

			 	$this->allow( $role , $regra );
			}
	}
}